﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "销售退货管理";
    Layout = null;
}
@Html.AntiForgeryToken()
<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>销售退货管理</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="searchForm" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">退货单编号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="returnNumber" placeholder="请输入退货单编号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">销售订单编号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="salesOrdersCode" placeholder="请输入销售订单编号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">客户名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="customeName" placeholder="请输入客户名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">仓库名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="returnsWarehouse" placeholder="请输入仓库名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">单据状态</label>
                        <div class="layui-input-inline">
                            <select name="documentStatus">
                                <option value="">全部</option>
                                <option value="0">草稿</option>
                                <option value="1">已确认</option>
                                <option value="2">已完成</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="searchForm">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            <div class="layui-btn-group" style="margin-bottom: 10px;">
                <button class="layui-btn" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 添加退货单
                </button>
                <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                    <i class="layui-icon layui-icon-delete"></i> 批量删除
                </button>
            </div>
            <table id="salesReturnsTable" lay-filter="salesReturnsTable"></table>
        </div>
    </div>
</div>
<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>
<!-- 弹窗表单模板 -->
<script type="text/html" id="formTpl">
    <form class="layui-form" lay-filter="mainForm" style="margin: 20px;">
        <input type="hidden" name="Id">
        <div class="layui-form-item">
            <label class="layui-form-label required">退货单编号</label>
            <div class="layui-input-inline" style="width: 70%;">
                <input type="text" name="ReturnNumber" required lay-verify="required" placeholder="退货单编号" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-input-inline" style="width: 28%;">
                <button type="button" class="layui-btn layui-btn-primary" id="genReturnNumberBtn">
                    <i class="layui-icon layui-icon-refresh"></i> 生成编号
                </button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">退货单名称</label>
            <div class="layui-input-block">
                <input type="text" name="ReturnName" required lay-verify="required" placeholder="请输入退货单名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">销售订单编号</label>
            <div class="layui-input-block">
                <input type="text" name="SalesOrdersCode" required lay-verify="required" placeholder="请输入销售订单编号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">客户编号</label>
            <div class="layui-input-inline">
                <input type="text" name="CustomeCode" lay-verify="required" placeholder="请选择客户" class="layui-input" readonly id="customerCodeInput">
                <i class="layui-icon layui-icon-search" id="selectCustomerBtn" style="position:absolute;right:10px;top:10px;cursor:pointer;"></i>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">客户名称</label>
            <div class="layui-input-inline">
                <input type="text" name="CustomeName" lay-verify="required" placeholder="请选择客户" class="layui-input" readonly id="customerNameInput">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">退货日期</label>
            <div class="layui-input-block">
                <input type="text" name="ReturnDate" id="returnDate" lay-verify="required" placeholder="请选择退货日期" class="layui-input" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">退货仓库</label>
            <div class="layui-input-inline">
                <input type="text" name="ReturnsWarehouse" required lay-verify="required" placeholder="请选择退货仓库" class="layui-input" readonly id="warehouseInput">
                <i class="layui-icon layui-icon-search" id="selectWarehouseBtn" style="position:absolute;right:10px;top:10px;cursor:pointer;"></i>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">单据状态</label>
            <div class="layui-input-block">
                <select name="DocumentStatus" required lay-verify="required" disabled>
                    <option value="0">草稿</option>
                    <option value="1">已确认</option>
                    <option value="2">已完成</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">退货原因</label>
            <div class="layui-input-block">
                <input type="text" name="ReasonReturn" placeholder="请输入退货原因" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitAddSalesReturns">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<!-- 工具条模板 -->
<script type="text/html" id="tableBar">
    {{#  if(d.documentStatus === 0){ }}
        <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
        <button class="layui-btn layui-btn-warm layui-btn-xs" lay-event="execute">执行退货</button>
    {{#  } else if(d.documentStatus ===2){ }}
        <span style="color:#52c41a;">已完成</span>
    {{#  } }}
</script>

<script type="text/html" id="customerSelectTpl">
    <div style="padding:20px;">
        <form class="layui-form" id="customerSearchForm" style="margin-bottom:10px;">
            <input type="text" name="customerName" placeholder="客户名称" class="layui-input" style="width:150px;display:inline-block;">

            <button class="layui-btn" lay-submit lay-filter="customerSearch">搜索</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
        <table class="layui-hide" id="customerTable" lay-filter="customerTable"></table>
        <div style="text-align:right;margin-top:10px;">
            <button class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
        </div>
    </div>
</script>

<script type="text/html" id="customerTableBar">
    <button class="layui-btn layui-btn-xs" lay-event="selectCustomer">选择</button>
</script>

<script type="text/html" id="warehouseSelectTpl">
    <div style="padding:20px;">
        <form class="layui-form" id="warehouseSearchForm" style="margin-bottom:10px;">
            <input type="text" name="depotCode" placeholder="仓库编号" class="layui-input" style="width:150px;display:inline-block;">
            <input type="text" name="depotName" placeholder="仓库名称" class="layui-input" style="width:150px;display:inline-block;">
            <input type="text" name="location" placeholder="位置" class="layui-input" style="width:150px;display:inline-block;">
            <button class="layui-btn" lay-submit lay-filter="warehouseSearch">搜索</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
        <table class="layui-hide" id="warehouseTable" lay-filter="warehouseTable"></table>
        <div style="text-align:right;margin-top:10px;">
            <button class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
        </div>
    </div>
</script>

<script type="text/html" id="warehouseTableBar">
    <button class="layui-btn layui-btn-xs" lay-event="selectWarehouse">选择</button>
</script>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.$;
        var laydate = layui.laydate;

        // 初始化表格
        function loadTable(params) {
            var searchParams = params || {};
            searchParams.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
            table.render({
                elem: '#salesReturnsTable',
                url: '/SalesReturns/GetSalesReturnsPaged',
                method: 'get',
                where: searchParams,
                page: true,
                limit: 10,
                height: 480,
                size: 'lg',
                even: true,
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'returnNumber', title: '退货单编号', width: 140, align: 'center'},
                    {field: 'returnName', title: '退货单名称', width: 140, align: 'center'},
                    {field: 'salesOrdersCode', title: '销售订单编号', width: 140, align: 'center'},
                    {field: 'customeCode', title: '客户编号', width: 140, align: 'center'},
                    {field: 'customeName', title: '客户名称', width: 120, align: 'center'},
                    {field: 'returnsWarehouse', title: '退货仓库', width: 120, align: 'center'},
                    {field: 'documentStatus', title: '单据状态', width: 100, align: 'center', templet: function(d){
                        switch(d.documentStatus){
                            case 0: return '<span class="layui-badge layui-bg-gray">草稿</span>';
                            case 1: return '<span class="layui-badge layui-bg-blue">已确认</span>';
                            case 2: return '<span class="layui-badge layui-bg-green">已完成</span>';
                            default: return d.documentStatus;
                        }
                    }},
                    {field:'returnDate', title:'退货日期', width:160, templet: d => d.returnDate ? d.returnDate.replace('T',' ').substring(0,16) : ''},
                    {field: 'reasonReturn', title: '退货原因', width: 160, align: 'center'},
                    {fixed: 'right', title: '操作', width:200, align: 'center', toolbar: '#tableBar'}
                ]],
                response: { statusCode: 0 },
                parseData: function(res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data || res.items || []
                    };
                }
            });
        }

        // 加载初始数据
        loadTable();

        // 查询按钮点击事件
        form.on('submit(searchForm)', function(data){
            loadTable(data.field);
            return false;
        });

        // 添加按钮点击事件
        $('#addBtn').on('click', function(){
            openForm();
        });

        // 打开表单
        function openForm(data) {
            // 兼容大小写
            var id = data && (data.Id !== undefined ? data.Id : data.id);
            var isEdit = id !== undefined && id !== null && id !== '' && id !== 0 && id !== '0';
            var title = isEdit ? '编辑退货单' : '添加退货单';
            layer.open({
                type: 1,
                title: title,
                area: ['500px', '600px'],
                content: $('#formTpl').html(),
                success: function(layero, index){
                    form.render(null, 'mainForm');
                    if(data){
                        form.val('mainForm', {
                            Id: id,
                            ReturnNumber: data.ReturnNumber || data.returnNumber,
                            ReturnName: data.ReturnName || data.returnName,
                            SalesOrdersCode: data.SalesOrdersCode || data.salesOrdersCode,
                            CustomeCode: data.CustomeCode || data.customeCode,
                            CustomeName: data.CustomeName || data.customeName,
                            ReturnDate: data.ReturnDate ? data.ReturnDate.split('T')[0] : (data.returnDate ? data.returnDate.split('T')[0] : ''),
                            ReturnsWarehouse: data.ReturnsWarehouse || data.returnsWarehouse,
                            DocumentStatus: data.DocumentStatus || data.documentStatus,
                            ReasonReturn: data.ReasonReturn || data.reasonReturn
                        });
                        if(data.ReturnDate || data.returnDate){
                            $(layero).find('#returnDate').val((data.ReturnDate || data.returnDate).split('T')[0]);
                        }
                        form.render(null, 'mainForm');
                    }
                    // 退货单编号唯一性校验（失焦时）
                    $(layero).find('input[name="ReturnNumber"]').off('blur').on('blur', function() {
                        var val = $(this).val();
                        if(!val) return;
                        $.get('/SalesReturns/CheckReturnNumberExists', { returnNumber: val }, function(res) {
                            if(res.code === 0 && res.exists) {
                                layer.msg('退货单编号已存在，请重新输入', {icon: 2});
                                $(layero).find('input[name="ReturnNumber"]').focus();
                            }
                        });
                    });
                    // 提交时也校验唯一性
                    form.on('submit(submitAddSalesReturns)', function(formData){
                        var formDataField = formData.field;
                        var isEdit = !!formDataField.Id && formDataField.Id !== '' && formDataField.Id !== '0';
                        // 新增时不传Id
                        if (!isEdit) {
                            delete formDataField.Id;
                        }
                        // 先校验编号唯一性
                        var isValid = true;
                        $.ajax({
                            url: '/SalesReturns/CheckReturnNumberExists',
                            type: 'GET',
                            data: { returnNumber: formDataField.ReturnNumber },
                            async: false,
                            success: function(res){
                                if(res.code === 0 && res.exists && !isEdit){
                                    layer.msg('退货单编号已存在，请重新输入', {icon: 2});
                                    isValid = false;
                                }
                            }
                        });
                        if(!isValid) return false;
                        // 日期格式兼容处理，空格替换为T
                        if (formDataField.ReturnDate) {
                            formDataField.ReturnDate = formDataField.ReturnDate.replace(' ', 'T');
                        }
                        // 为POST请求加上防伪Token
                        formDataField.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
                        $.ajax({
                            url: isEdit ? '/SalesReturns/Update' : '/SalesReturns/AddSalesReturns',
                            type: 'POST',
                            data: formDataField,
                            // contentType: 'application/x-www-form-urlencoded', // 注释掉contentType
                            success: function(res){
                                if(res.code === 0){
                                    layer.close(index);
                                    layer.msg((isEdit ? '修改' : '添加') + '成功');
                                    table.reload('salesReturnsTable');
                                }else{
                                    var msg = res.msg;
                                    if(res.errors){
                                        msg += '<br>' + (Array.isArray(res.errors) ? res.errors.join('<br>') : JSON.stringify(res.errors));
                                    }
                                    layer.msg(msg);
                                }
                            },
                            error: function(xhr){
                                var msg = '请求失败';
                                if(xhr.responseJSON && xhr.responseJSON.msg){
                                    msg = xhr.responseJSON.msg;
                                    if(xhr.responseJSON.errors){
                                        msg += '<br>' + (Array.isArray(xhr.responseJSON.errors) ? xhr.responseJSON.errors.join('<br>') : JSON.stringify(xhr.responseJSON.errors));
                                    }
                                }
                                layer.msg(msg);
                            }
                        });
                        return false;
                    });

                    // 客户选择弹窗
                    $('#selectCustomerBtn,#customerCodeInput,#customerNameInput').off('click').on('click', function(){
                        var customerLayerIndex = layer.open({
                            type: 1,
                            title: '选择客户',
                            area: ['600px','400px'],
                            content: $('#customerSelectTpl').html(),
                            success: function(){
                                var customerTableIns = table.render({
                                    elem: '#customerTable',
                                    url: '/SalesReturns/ShowCustomer',
                                    method: 'get',
                                    page: true,
                                    request: {
                                        pageName: 'pageIndex',
                                        limitName: 'pageSize'
                                    },
                                    cols: [[
                                        {field:'id', title:'ID', width:80},
                                        {field:'customerCode', title:'客户编号', width:120},
                                        {field:'customerName', title:'客户名称', width:180},
                                        {title:'操作', width:100, align:'center', toolbar:'#customerTableBar'}
                                    ]],
                                    response: { statusCode: 0 },
                                    parseData: function(res){
                                        return { code: res.code, msg: res.msg, count: res.count, data: res.data };
                                    }
                                });
                                // 搜索
                                form.on('submit(customerSearch)', function(data){
                                    customerTableIns.reload({ where: data.field, page: {curr: 1} });
                                    return false;
                                });
                                // 监听选择按钮
                                table.on('tool(customerTable)', function(obj){
                                    if(obj.event === 'selectCustomer'){
                                        $('#customerCodeInput').val(obj.data.customerCode);
                                        $('#customerNameInput').val(obj.data.customerName);
                                        layer.close(customerLayerIndex);
                                    }
                                });
                            }
                        });
                    });

                    // 仓库选择弹窗
                    $('#selectWarehouseBtn,#warehouseInput').off('click').on('click', function(){
                        var warehouseLayerIndex = layer.open({
                            type: 1,
                            title: '选择退货仓库',
                            area: ['600px','400px'],
                            content: $('#warehouseSelectTpl').html(),
                            success: function(){
                                var warehouseTableIns = table.render({
                                    elem: '#warehouseTable',
                                    url: '/SalesReturns/GetWarehouseSettings',
                                    method: 'get',
                                    page: true,
                                    cols: [[
                                        {field:'id', title:'ID', width:60},
                                        {field:'depotCode', title:'仓库编号', width:120},
                                        {field:'depotName', title:'仓库名称', width:150},
                                        {field:'location', title:'位置', width:150},
                                        {field:'area', title:'面积(㎡)', width:100},
                                        {field:'head', title:'负责人', width:100},
                                        {field:'remark', title:'备注', width:100},
                                        {title:'操作', width:100, align:'center', toolbar:'#warehouseTableBar'}
                                    ]],
                                    response: { statusCode: 0 },
                                    parseData: function(res){
                                        return { code: res.code, msg: res.msg, count: res.count, data: res.data };
                                    }
                                });
                                // 搜索
                                form.on('submit(warehouseSearch)', function(data){
                                    warehouseTableIns.reload({ where: data.field, page: {curr: 1} });
                                    return false;
                                });
                                // 监听选择按钮
                                table.on('tool(warehouseTable)', function(obj){
                                    if(obj.event === 'selectWarehouse'){
                                        $('#warehouseInput').val(obj.data.depotName);
                                        layer.close(warehouseLayerIndex);
                                    }
                                });
                            }
                        });
                    });

                    // 初始化退货日期选择器
                    laydate.render({
                        elem: '#returnDate',
                        type: 'datetime' // 如果只要日期可用 'date'
                    });

                    // 在openForm的success回调中绑定按钮事件
                    $(layero).find('#genReturnNumberBtn').off('click').on('click', function() {
                        $.get('/SalesReturns/GetNewReturnNumber', function(res) {
                            if(res.code === 0) {
                                $(layero).find('input[name="ReturnNumber"]').val(res.returnNumber).trigger('blur');
                            } else {
                                layer.msg(res.msg || '获取退货单编号失败');
                            }
                        });
                    });
                }
            });
        }

        // 表格操作事件
        table.on('tool(salesReturnsTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                // 用id请求后端获取详情再反填
                $.get('/SalesReturns/GetById', { id: data.id }, function(res){
                    if(res.code === 0 && res.data){
                        openForm(res.data);
                    }else{
                        layer.msg(res.msg || '获取数据失败');
                    }
                });
            } else if(obj.event === 'del'){
                layer.confirm('确定要删除该退货单吗？', function(index){
                    $.ajax({
                        url: '/SalesReturns/Delete',
                        type: 'POST',
                        data: { id: data.id, __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() },
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('删除成功');
                                obj.del();
                            }else{
                                layer.msg(res.msg || '删除失败');
                            }
                        },
                        error: function(){
                            layer.msg('请求失败');
                        }
                    });
                    layer.close(index);
                });
            } else if(obj.event === 'execute'){
                layer.confirm('确定要将该退货单状态改为已完成吗？', function(index){
                    $.ajax({
                        url: '/SalesReturns/UpdateStatus',
                        type: 'POST',
                        data: { id: data.id, newStatus: 1, __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() },
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('退货已完成');
                                table.reload('salesReturnsTable');
                            }else{
                                layer.msg(res.msg || '操作失败');
                            }
                        },
                        error: function(){
                            layer.msg('请求失败');
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 批量删除按钮事件
        $('#batchDeleteBtn').on('click', function(){
            var checkStatus = table.checkStatus('salesReturnsTable');
            var selected = checkStatus.data || [];
            if(selected.length === 0){
                layer.msg('请先选择要删除的退货单');
                return;
            }
            // 只允许删除草稿状态
            var invalid = selected.filter(function(item){
                var status = item.documentStatus !== undefined ? item.documentStatus : item.DocumentStatus;
                return status !== 0 && status !== '0';
            });
            if(invalid.length > 0){
                layer.msg('只能批量删除草稿状态的退货单');
                return;
            }
            var ids = selected.map(function(item){ return item.id || item.Id; });
            layer.confirm('确定要批量删除选中的退货单吗？', function(index){
                $.ajax({
                    url: '/SalesReturns/BatchDelete',
                    type: 'POST',
                    data: { ids: ids, __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() },
                    traditional: true,
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('批量删除成功');
                            table.reload('salesReturnsTable');
                        }else{
                            layer.msg(res.msg || '批量删除失败');
                        }
                    },
                    error: function(){
                        layer.msg('请求失败');
                    }
                });
                layer.close(index);
            });
        });
    });
</script>

<style>
    .layui-form-label.required:after {
        content: '*';
        color: red;
        margin-left: 4px;
    }

    .layui-card {
        margin: 15px;
    }

    .layui-form-item {
        margin-bottom: 15px;
    }
</style>
